/*
 * by: chenming
 * date: 2023/4/20
 * desc:
 * */

import { defineStore } from 'pinia';
import { getLang } from '@/api/lang';
import { getLangModules } from '@/utils/lang';
import { LangState } from './types';

const useLangStore = defineStore('lang', {
  state: (): LangState => {
    return {
      lang: {},
    };
  },
  getters: {
    getterLang(state: LangState) {
      return state.lang;
    },
  },
  actions: {
    setLang(langs: any) {
      const onlineLang = langs;
      const localLang = getLangModules();
      const onlineLangKeys: string[] = Object.keys(onlineLang);
      const localLangKeys: string[] = Object.keys(localLang);
      if (onlineLangKeys.length) {
        const keys: string[] = [];
        localLangKeys.forEach((key) => {
          if (onlineLangKeys.indexOf(key) < 0) {
            keys.push(key);
          }
        });
        keys.forEach((key) => {
          // @ts-ignore
          onlineLang[key] = localLang[key];
        });
        this.lang = onlineLang;
      } else {
        this.lang = localLang;
      }
    },
    async getLanguages(langEnv: string) {
      let onlineLang = {};
      await getLang(langEnv).then((res) => {
        onlineLang = res.data || {};
      });
      this.setLang(onlineLang);
      localStorage.setItem('lang_env', langEnv);
    },
  },
});

export default useLangStore;
